using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using PocketPals.Data;
using PocketPals.Models;
using System.Threading.Tasks;

namespace PocketPals.Controllers
{
    public class BalanceController : Controller
    {
        private readonly ApplicationDbContext _context;

        public BalanceController(ApplicationDbContext context)
        {
            _context = context;
        }

        /// <summary>
        /// 显示当前余额信息
        /// </summary>
        /// <returns>余额视图</returns>
        public async Task<IActionResult> Index()
        {
            // 获取最新的余额记录
            var latestBalance = await _context.Balances
                .OrderByDescending(b => b.UpdatedAt)
                .FirstOrDefaultAsync();

            // 如果没有余额记录，创建一个默认的余额对象
            if (latestBalance == null)
            {
                latestBalance = new Balance
                {
                    Id = Guid.NewGuid(),
                    Amount = 0,
                    OperationAmount = 0,
                    BeforeAmount = 0,
                    AfterAmount = 0,
                    UpdatedAt = DateTime.Now
                };
            }

            // 获取最近的交易记录
            var recentTransactions = await _context.Transactions
                .OrderByDescending(t => t.TransactionTime)
                .Take(5)
                .ToListAsync();

            // 创建视图模型
            var viewModel = new BalanceViewModel
            {
                CurrentBalance = latestBalance,
                RecentTransactions = recentTransactions
            };

            return View(viewModel);
        }
    }
}